package com.zgjkhis.modules.quartz.task;

import cn.hutool.core.util.ArrayUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zgjkhis.modules.charges.domain.Logistics;
import com.zgjkhis.modules.charges.domain.LogisticsRoute;
import com.zgjkhis.modules.charges.domain.PrescriptionOrder;
import com.zgjkhis.modules.charges.service.LogisticsRouteService;
import com.zgjkhis.modules.charges.service.LogisticsService;
import com.zgjkhis.modules.charges.service.PrescriptionService;
import com.zgjkhis.modules.system.domain.Info;
import com.zgjkhis.modules.system.domain.Store;
import com.zgjkhis.modules.system.service.InfoService;
import com.zgjkhis.modules.system.service.StoreService;
import com.zgjkhis.modules.util.LogisticsUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName LogisticsTask
 * @Deacription TODO
 * @Author yzq
 * @Date 2021/7/31 15:02
 * @Version 1.0
 **/
@Slf4j
@Component
public class LogisticsTask {


    private final String baseUrl="";

    @Resource
    private LogisticsService logisticsService;
    @Resource
    private LogisticsRouteService routeService;
    @Resource
    private PrescriptionService prescriptionService;
    @Resource
    private StoreService storeService;
    @Resource
    private InfoService infoService;



    /**
     *  查询物流
     *  间隔2小时查询一次
     */
    public void queryLogistics() {
        log.info(String.format(".................... task.queryLogistics start"));
        List<Logistics> list = this.logisticsService.queryNoComplete();
        List<LogisticsRoute> routes;
        if(!ArrayUtil.isEmpty(list)) {
            for(Logistics item: list) {
                routes = this.requestOrderRoute(item);
                if(!ArrayUtil.isEmpty(routes)) {
                    this.routeService.batchDelRoute(item.getBspOrderNo());
                    this.routeService.saveBatch(routes);
//                    this.checkLogistics(item, routes);
                }
            }
        }
        log.info(String.format(".................... task.queryLogistics end"));
    }

    private List<LogisticsRoute> requestOrderRoute(Logistics logistics) {
        Store store=storeService.getFromCatchById(logistics.getPharmacyId());

        String result = LogisticsUtil.listOrderRoute(logistics.getMailNo(), store.getAppId(), store.getAppIdSecret(),baseUrl);
        JSONObject temp=JSONObject.parseObject(result);
        if(!"200".equals(temp.getString("code"))){
            String message = temp.getString("msg");
            log.info(String.format("物流信息查询失败:%s", message));
            return null;
        }
        JSONObject jsonObject = temp.getJSONObject("data");
        JSONArray array=jsonObject.getJSONArray("route");
        List<LogisticsRoute> routes = new ArrayList<>();
        if(array.size() > 0) {
            Integer orderStatus=jsonObject.getInteger("orderStatus");
            logistics.setStatus(orderStatus);
            this.logisticsService.updateById(logistics);
            if(3==orderStatus) {
                prescriptionService.update(Wrappers.<PrescriptionOrder>update().lambda().set(PrescriptionOrder::getOrderCondition, 4).eq(PrescriptionOrder::getOrderNo, logistics.getOrderNo()));
                infoService.update(Wrappers.<Info>update().lambda().set(Info::getOrderCondition, 4).eq(Info::getOrderNo, logistics.getOrderNo()));
            }
            array.forEach(item -> {
                routes.add(new LogisticsRoute((JSONObject) item, logistics));
            });
        }
        return routes;
    }

    private void checkLogistics(Logistics logistics, List<LogisticsRoute> routes) {
        for(LogisticsRoute route: routes) {
            int code = route.getOpcode().intValue();
            // 80或8000已签收
            if(code == 80 || code == 8000) {
                log.info(String.format("已签收，bspOrderNo: %s", logistics.getBspOrderNo()));
                logistics.setStatus(3);
                this.logisticsService.updateById(logistics);
                prescriptionService.update(Wrappers.<PrescriptionOrder>update().lambda().set(PrescriptionOrder::getOrderCondition, 4).eq(PrescriptionOrder::getOrderNo,logistics.getOrderNo()));
//                LogisticsUtil.sendLogistic(logistics.getBspOrderNo(), logistics.getOrderNo().split(","),logistics.getMailNo(),"3");
                break;
            }
        }
    }

}
